package com.example.freshfoodproject.controller;
import com.example.freshfoodproject.Dto.OrderArr;
import com.example.freshfoodproject.entry.Orders;
import com.example.freshfoodproject.entry.Shopping;
import com.example.freshfoodproject.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 添加所有支付表中所需要的信息
     * @param orderArr 包含了:List<Shopping>的集合，集合里为购物车里所勾选的商品信息；
     *                 paymentMethod:支付方式；
     *                 timestamp:支付的系统时间；
     *                 status:支付的状态(分为已支付和未支付的状态)
     *                 code:订单号
     */
    @PostMapping ("/addOrder")
    @ResponseBody
    public void addOrder(@RequestBody OrderArr orderArr){
        String randomNumber = String.valueOf(ThreadLocalRandom.current().nextInt(10000000, 100000000));
        for (Shopping item : orderArr.getSelectedItems()) {
            Orders orders = new Orders();
            orders.setOrderGoods(item.getPurchaseItems());
            orders.setOrderNumber(item.getPurchaseNumber());
            orders.setPrice(item.getPurchasePrice()/item.getPurchaseNumber());
            orders.setPicture(item.getPicture());
            orders.setOrderType(orderArr.getStatus());
            orders.setPayment(orderArr.getPaymentMethod());
            orders.setDaytime(orderArr.getTimestamp());
            orders.setOrderCode(randomNumber);
            orderService.addOrder(orders);
        }
    }

    /**
     *从数据库中查询订单数据，将其按照订单编号分组，对同一订单中重复的商品合并数量后，
     * 组装成包含订单详情（如编号、时间、支付方式、状态等）和商品详情（如名称、数量、价格、图片等）的结构化对象列表，
     * 并返回给前端用于展示。每次遇到订单编号变化或到达最后一条数据时，将当前订单的商品列表封装成一个完整的订单对象加入返回结果，
     * 同时清空商品列表以处理下一个订单。
     * @return
     */
    @RequestMapping("findOrders")
    @ResponseBody
    public List<OrderArr> findOrders() {
        List<OrderArr> orderAll = new ArrayList<>();
        OrderArr orderArr = null;
        List<Shopping> list = new ArrayList<>();
        List<Orders> orders = orderService.findOrders();
        for (int i = 0; i < orders.size(); i++) {
            boolean isNewOrder = true;
            for (int j = 0; j < list.size(); j++) {
                if (list.get(j).getPurchaseItems().equals(orders.get(i).getOrderGoods())) {
                    // 更新已有商品信息
                    list.get(j).setPurchaseNumber(list.get(j).getPurchaseNumber() + orders.get(i).getOrderNumber());
                    isNewOrder = false;
                    break;
                }
            }
            if (isNewOrder) {
                // 新增商品信息
                Shopping shopping = new Shopping();
                shopping.setPurchaseItems(orders.get(i).getOrderGoods());
                shopping.setPurchaseNumber(orders.get(i).getOrderNumber());
                shopping.setPicture(orders.get(i).getPicture());
                shopping.setPurchasePrice(orders.get(i).getPrice());
                list.add(shopping);
            }
            // 检查是否是新订单
            if (i == orders.size() - 1 || !orders.get(i).getOrderCode().equals(orders.get(i + 1).getOrderCode())) {
                orderArr = new OrderArr();
                orderArr.setSelectedItems(new ArrayList<>(list)); // 克隆当前商品列表
                orderArr.setPaymentMethod(orders.get(i).getPayment());
                orderArr.setStatus(orders.get(i).getOrderType());
                orderArr.setTimestamp(orders.get(i).getDaytime());
                orderArr.setCode(orders.get(i).getOrderCode());
                orderAll.add(orderArr);
                // 重置商品列表
                list.clear();
            }
        }
        System.out.println(orderAll);
        return orderAll;
    }

    /**
     * 将此订单号的所有数据删除
     * @param orderCode 订单号
     */
    @RequestMapping("deleteCode")
    @ResponseBody
    public void deleteCode(String orderCode){
        System.out.println(orderCode+"==========");
        orderService.removeCode(orderCode);
    }

}
